from flask import Blueprint, jsonify, request

from app.mappers.DepartmentInfoDao import DepartmentInfoDao
from app.mappers.models import DepartmentInfo, DepartmentInfoSchema

department_info_bp = Blueprint("department_info_controller", __name__)
departmentDao = DepartmentInfoDao()


@department_info_bp.route('/find-all', methods=["GET"])
def findAll():
    departInfo = departmentDao.findAll()
    departInfoSchema = DepartmentInfoSchema(many=True)
    departInfoData = departInfoSchema.dump(departInfo)
    resultMsg = {"code": 200, "data": departInfoData, "msg": "操作成功"}
    return jsonify(resultMsg)


@department_info_bp.route('/add-one', methods=["POST"])
def addOne():
    resultMsg = {"code": "200", "msg": "操作成功"}
    request_body = request.get_json()
    id = request_body["id"]
    name = request_body["name"]

    department = DepartmentInfo(id=id, name=name)
    flag = departmentDao.addOne(department)

    if flag:
        resultMsg["code"] = 200
        resultMsg["msg"] = "操作成功"
    else:
        resultMsg["code"] = 201
        resultMsg["msg"] = "操作失败"

    return jsonify(resultMsg)


@department_info_bp.route("delete-one", methods=["GET"])
def deleteOne():
    # 返回值
    resultMsg = {"code": "200", "msg": "操作成功"}

    # 从查询参数中获取ID
    id = request.args.get('id')

    # 修改文学类型
    flag = departmentDao.deleteById(id)

    if flag:
        resultMsg["code"] = 200
        resultMsg["msg"] = "操作成功"
    else:
        resultMsg["code"] = 201
        resultMsg["msg"] = "操作失败"

    return jsonify(resultMsg)


@department_info_bp.route("/update-one", methods=["POST"])
def updateOne():
    resultMsg = {"code": "200", "msg": "操作成功"}
    request_body = request.get_json()
    id = request_body.get("id")
    name = request_body.get("name")

    flag = departmentDao.updateById(id, name)

    if flag:
        resultMsg["code"] = 200
        resultMsg["msg"] = "操作成功"
    else:
        resultMsg["code"] = 201
        resultMsg["msg"] = "操作失败"

    return jsonify(resultMsg)
